package com.vrv.common.resolver.dispatcher;

import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.vrv.common.resolver.RequestParameter;
import com.vrv.common.resolver.Response;
import com.vrv.common.resolver.locality.DBManager;

public class LocalityChartRequestHandler implements RequestState {

    @Override
    public Response handler(Context mContext, RequestParameter parameter, String[] detailKeys) {
        String uri = parameter.getUrl();
        String tableName = uri.substring(uri.lastIndexOf("/") + 1);
        String sql = "SELECT * from " + tableName + " WHERE 1=1 " + getFilterSql(parameter);
        Response response = new Response();
        try {
            Map<String, Object> record = new HashMap<String, Object>();
            DBManager.getInstance(mContext).open();
            SQLiteDatabase sqliteDb = DBManager.getInstance(mContext).getMSQLiteDatabase();
            Cursor mCursor = sqliteDb.rawQuery(sql, null);

            while (mCursor.moveToNext()) {
                for (int i = 0; i < detailKeys.length; i++) {
                    int columnIndex = mCursor.getColumnIndex(detailKeys[i]);
                    if (!record.containsKey(detailKeys[i])) {
                        String[] vals = new String[mCursor.getCount()];
                        setValue(mCursor, columnIndex, vals);
                        record.put(detailKeys[i], vals);
                    } else {
                        String[] vals = (String[]) record.get(detailKeys[i]);
                        setValue(mCursor, columnIndex, vals);
                        record.put(detailKeys[i], vals);
                    }
                }
            }

            DBManager.getInstance(mContext).close();
            response.setTotalRecords(record.size() > 0 ? 1 : 0);
            response.setRecord(record);
            response.setSuccess(Boolean.TRUE);
            return response;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 根据相关类型转换成Number
     *
     * @param mCursor
     * @param columnIndex
     * @param vals
     */
    private void setValue(Cursor mCursor, int columnIndex, Object[] vals) {
        vals[mCursor.getPosition()] = mCursor.getString(columnIndex);
    }

    private String getFilterSql(RequestParameter parameter) {
        return "";
    }

}
